<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Models\Cates;
use DB;
use App\Http\Controllers\Controller;

class CatesController extends Controller
{
    public static function getCatesByPid($pid)
    {
        $res = Cates::where('pid', $pid)->get()->toArray();
        $data = [];

        foreach ($res as $k=>$v){
            $v['sub'] = self::getCatesByPid($v['id']);
            $data[] = $v;
        }
        return $data;
    }

    public static function getCates()
    {
        $cates = Cates::select(DB::raw('*,concat(path,",",id) npath'))->orderby('npath')->get()->toArray();
        foreach($cates as $k=>$v){
            $len = substr_count($v['path'], ',');
            $cates[$k]['name'] = str_repeat('|--', $len).$v['name'];
        }
        return $cates;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex(Request $request)
    {
        //
        $num = $request->num ?? 10;
        $keywords = $request->keywords ?? "";

        $cates = self::getCates();
//        dd($cates);
//        foreach($cates as $k => $v){
//            if($v['path'] == '0')
//        }

        return view('Admin/Cates/index',['cates'=> $cates, 'num'=> $num, 'keywords'=>$keywords]);

    }


    public function getAdd($id=''){

        $cates = self::getCates();

        return view('Admin/Cates/add',['cates'=>$cates, 'id'=>$id]);
    }

    public function postInsert(Request $request){
        // 去除 _token
        $data = $request->except('_token');
        //验证分类信息
        $this->validate($request, [
            'name' => 'required',
        ],[
            'name.required'=>'分类名称不能为空',
        ]);

        $pid = $request->pid;

        // 拼写路径
        if( $pid == 0){
            $data['path'] = '0';
        }else{
            $path = Cates::where('id', $pid)->first()->toArray()['path'];
            $data['path'] = $path.','.$data['pid'];
        }

        $data['created_at'] = $data['updated_at'] = date('Y-m-d H:i:s', time());
        $res = Cates::insert($data);
        if($res){
            return redirect('/admin/cates/index')->with('success', $data['name'].'添加成功');
        }else{
            return back()->with('error', $data['name'].'添加失败');  //返回上一页
        }
    }


    public function getDelete($id){

        $res = Cates::where('pid', $id)->get()->toArray();

        if(!empty($res)){
            return back()->with('error', '该分类下有子类，请慎重选择');
        }else{
            //此处其实应当再做判断,判断最底层子类下,是否有商品信息,若有商品信息,也不能删除
            $info = Cates::where('id',$id)->delete();

            //判断是否删除成功
            if($info){
                return redirect('admin/cates/index')->with('success','类别删除成功!');
            }else{
                return back()->with('error','类别删除失败!');
            }
        }
    }

    public function getList()
    {
        dd(self::getCatesByPid(0));
//        self::getCatesByPid(0);
    }

    public function getEdit($id)
    {
        //通过id查询出正在进行修改的分类名称
        $res = Cates::select('id', 'name')->where('id', $id)->first()->toArray();
        return view('Admin/Cates/edit', ['res'=>$res]);
    }

    // 执行信息修改的方法
    public function postUpdate(Request $request)
    {
        $id = $request->id;
        $info = $request->except(['_token', 'id']);
        $res = Cates::where('id', $id)->update($info);
        if($res){
            return redirect('admin/cates/index')->with('success','类别名称修改成功!');
        }else{
            return back()->with('error', '类别名称修改失败！');
        }
    }


}
